package com.lock.test.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: alexxiao
 * @date: 2023/3/8 11:44
 * <p>
 */
@Service
public class CacheServiceImpl implements CacheService {
    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setKey(String key, String value) {
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, value);
    }

    @Override
    public void setKey(String key, String value, long timeOut, TimeUnit unit) {
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, value, timeOut, unit);
    }

    @Override
    public String getValue(String key) {
        ValueOperations<String, String> ops = template.opsForValue();
        return ops.get(key);
    }

    @Override
    public Boolean lock(String key) {
        ValueOperations<String, String> ops = template.opsForValue();
        Boolean lock = ops.setIfAbsent(key, "1");
        if (lock) {
            template.expire(key, 30, TimeUnit.SECONDS);
            return true;
        }
        return false;
    }

    @Override
    public Boolean lock(String key, long timeOut, TimeUnit unit) {
        ValueOperations<String, String> ops = template.opsForValue();
        Boolean lock = ops.setIfAbsent(key, "1");
        if (lock) {
            template.expire(key, timeOut, unit);
            return true;
        }
        return false;
    }
}

